﻿using System.Linq;
using System.Web.Mvc;
using Icms.Core.Security;
using Icms.Core.Service;
using Icms.WebUI.Dto;

namespace Icms.WebUI.Controllers
{
    public class AccountController : BaseController
    {
        private readonly IFormsAuthentication formsAuth;
        private readonly IUserService userService;

        public AccountController(IFormsAuthentication formsAuth, IUserService userService)
        {
            this.formsAuth = formsAuth;
            this.userService = userService;
        }

        public ActionResult SignIn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult SignIn(SignInInput input)
        {
            if (!ModelState.IsValid)
            {
                input.Password = null;
                input.Login = null;
                return View(input);
            }

            var user = userService.Where(o => o.Login == input.Login && o.Password == input.Password).SingleOrDefault();
            if ( user == null)
            {
                ModelState.AddModelError("","Numele sau parola nu sunt introduse corect, va rugam sa mai incercati o data");
                return View();
            }

            formsAuth.SignIn(user.Login, input.Remember, user.Roles.Select(o => o.Name));

            return RedirectToAction("Index", "Home");

        }

        public ActionResult SignOff()
        {
            formsAuth.SignOut();
            return RedirectToAction("SignIn", "Account");
        }
    }
}